package com.googlecode.cswish.security.type;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.googlecode.cswish.security.Context;


/**
 * @author Jerry.Feng Date: 2008-6-11
 */
public class RecordRuleSetOr extends RuleSetOr implements Calculation {
	
	public final static RecordRuleSetOr FALSE = new RecordRuleSetOr() {
		@Override
		public String execute(Context context) {
			return "false";
		}
		
		@Override
		public String getWhereClause(Context context) {
			return "1<>1";
		}
	};
	
	private String fromClause;
	
	public String getFromClause() {
		return fromClause;
	}

	public String getWhereClause(Context context) {
		return execute(context);
	}

	@Override
	public String execute(Context context) {
		String whereClause;
		if (expressList.size() > 0) {
			StringBuilder sb = new StringBuilder();
			Set<String> fromClauseSet = new HashSet<String>();
			for (Iterator<Calculation> iter = expressList.iterator(); iter.hasNext();) {
				Calculation expression = iter.next();
				
				String expressionResult = expression.execute(context);
				if (StringUtils.isNotEmpty(expressionResult)) {
					sb.append(" or (").append(expressionResult).append(")");
				}
				
				if (expression instanceof PermissionRule) {
					PermissionRule permissionRule = (PermissionRule)expression;
					if (permissionRule.getFromClause() != null) {
						fromClauseSet.add(permissionRule.getFromClause());
					}
				}
			}
			if (!fromClauseSet.isEmpty()) {
				fromClause = StringUtils.join(fromClauseSet, ' ');
			}
			
			// remove the first " or "
			if (sb.length() > 4) {
				whereClause = sb.substring(4);
			} else {
				whereClause = "true";
			}
		} else {
			whereClause = "true";
		}
		return whereClause;
	}
}